//
//  LightsInfoVC.m
//  SuperLight
//
//  Created by Charlie Liao on 14-4-30.
//  Copyright (c) 2014年 Charlie Liao. All rights reserved.
//

#import "LightsInfoVC.h"

@interface LightsInfoVC ()

@end

@implementation LightsInfoVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (self.type == modificationInfoType) {
        self.title = @"Update";
    } else {
        self.title = @"Add";
    }
    
    self.nameTextField.text = self.name;
    self.addrTextField.text = self.addr;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(onClickSaveBtn)];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.nameTextField becomeFirstResponder];
}

#pragma mark  UITextField Delegate

static char* digits = "0123456789abcdefABCDEF";

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {
        return YES;
    } else if (textField.text.length >= 8) {
        return NO;
    } else {
        for (int i= 0; i < 22; i++) {
            if ([string isEqualToString:[NSString stringWithFormat:@"%c", digits[i]]]) {
                return YES;
            }
        }
        return NO;
    }
}

#pragma mark  Action

- (void)onClickSaveBtn
{
    if (self.nameTextField.text == nil || [self.nameTextField.text isEqualToString:@""] || [self.nameTextField.text isEqual:[NSNull null]]) {
        return;
    }
    
    if (self.addrTextField.text == nil || [self.addrTextField.text isEqualToString:@""] || [self.addrTextField.text isEqual:[NSNull null]]) {
        return;
    }
    
    LightEntity *entity = nil;
    if (self.type == modificationInfoType) {
        entity = [Common share].lightsArr[self.index];
        entity.name = self.nameTextField.text;
        entity.addr = self.addrTextField.text;
    } else {
        entity = [[LightEntity alloc] initWithName:self.nameTextField.text AndAddr:self.addrTextField.text];
        [[Common share].lightsArr addObject:entity];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
